var util = require('../base/Util');
var express = require('express');
var  router = express.Router();
//数据库操作对象
var DbOpt = require("../models/Dbopt");
// 展示菜式
var WeixinShow = require("../models/WeixinShow");
// 菜式
var Cuisine = require("../models/Cuisine");



var pageSize = 20;


router.post("/update", function (req, res) {
    var addData = {}, conditions = {};
    var cstype = req.body.cstype;
    var dis = req.body.dis;
    var week = req.body.week;
    var price= req.body.price;

    if (cstype != null && cstype != "") {
        addData["cstype"] = cstype;
    }
    if (dis != null && dis != "") {
        addData["dis"] = req.body.dis;
    }
    if (price != null && price != "") {
        addData["price"] =price;
    }

    var id = req.body.id;
    conditions["csid"] = id;
    conditions["week"] = week;
    console.log(conditions);
    DbOpt.update(WeixinShow,conditions,addData,function(){
        res.json({success: 1});
    });

});


router.post("/add", function (req, res) {
    var queryCondition = {};
    queryCondition["week"] = req.body.week;
    queryCondition["csid"] = req.body.id;
    DbOpt.pagination(WeixinShow,queryCondition,1,999,function(qinfo){
        if (qinfo.totalItems <= 0) {
            var remark = req.body.remark;
            var buyItems = req.body.buyItems;
            var addData = {};
            addData["csid"] = req.body.id;
            addData["name"] = req.body.name;
            addData["week"] = req.body.week;
            addData["dis"] = req.body.dis;
            addData["cstype"] = req.body.type;
            addData["time"] = new Date();
            DbOpt.addOne(WeixinShow,addData,function(){
                res.json({success: 1});
            });
        } else {
            res.json({success: 1});
        }
    });

});


router.get("/init", function (req, res) {
    var week = req.query.week;
    var queryCondition = {};
    if (week == null || week == "") {
        week = new Date().getDay();
        week = week == 0 ? week = 7 : week;
    }
    queryCondition["week"] = week + "";
    DbOpt.findAll(Cuisine,function(cuisines){
        DbOpt.pagination(WeixinShow,queryCondition,1,999,function(qinfo){
            res.render("weixinshow/weixinshow", {
                weixinshows: qinfo.docs,
                cuisines: cuisines,
                week: week
            });
        });
    })
});


router.get("/del", function (req, res) {
    var id = req.query.id;
    var week = req.query.week;
    var conditions = {};
    conditions["csid"] = id;
    conditions["week"] = week;
    console.log(conditions);
    DbOpt.delByCondition(WeixinShow,conditions,function(){
        res.json({success: 1});
    });

});


module.exports = router;